import numpy as np
import matplotlib.pyplot as plt
colors=['darkorange','blue','deeppink','black','limegreen','green','teal']
#点标记的样式 ^表示三角形，*五角星，o圆点，3箭头
markers=['s-','o-','x-','d-','^-','p-','*-']
scale = [1,2,3,4,5,6,7,8,9,10]
figsize=[6,5]
dpi=300
fontsize=12
linewidth=2.7
markersize=12

def draw(ddlList:list[int],filename:str):
    utilityDict = {}
    timeDict = {}
    memoryDict = {}
    responseDict = {}
    matchSizeDict = {}
    method = ''
    with open(filename, "r") as f:
        for item in f.readlines():
            items = item.split(" ")
            if method != items[0]:
                method = items[0]
                utilityDict.update({method: [float(items[1])]})
                timeDict.update({method: [float(items[2])]})
                memoryDict.update({method: [float(items[3])]})
                # responseDict.update({method:[float(items[4])]})
                matchSizeDict.update({method:[float(items[4])]})
            else:
                utilityDict[method].append(float(items[1]))
                timeDict[method].append(float(items[2]))
                memoryDict[method].append(float(items[3]))
                # responseDict[method].append(float(items[4]))
                matchSizeDict[method].append(float(items[4]))
    drawUtility(utilityDict,ddlList)
    drawTime(timeDict,ddlList)
    drawMemory(memoryDict,ddlList)
    # drawResponse(responseDict,ddlList)
    drawMatchSize(matchSizeDict,ddlList)

def drawUtility(utilityDict:dict,idx:list[int]):
    plt.figure(figsize=(figsize[0], figsize[1]), dpi=dpi)
    # plt.rcParams['font.sans-serif'] = ['STSong']  # 显示汉字
    plt.xlabel('$c_{w}$', fontsize=fontsize+6)  # x轴标题
    plt.ylabel('Utility', fontsize=fontsize+6)  # y轴标题
    plt.tick_params(labelsize=fontsize)
    #自定义横坐标的刻度
    # scale = np.arange(len(idx))
    plt.xticks(scale, idx)

    ax = plt.gca()
    ax.ticklabel_format(style='sci', scilimits=(-1, 2), axis='y', useMathText='%.2f×10$^{4}$')
    ax.get_yaxis().get_offset_text().set(va='bottom', ha='left')
    ax.yaxis.get_offset_text().set_fontsize(8)

    colorNum = 0
    itemName = []
    for item in utilityDict:
        itemName.append(item)
        plt.plot(scale,utilityDict[item], markers[colorNum], color=colors[colorNum], linewidth=linewidth, markersize=markersize,
                 markerfacecolor='none')
        colorNum += 1
    # plt.legend(itemName,loc=10, bbox_to_anchor=(0.5, 0.7))  # 设置折线名称
    plt.legend(itemName)  # 设置折线名称
    # plt.show()
    plt.savefig("picture/gMissionUtility.png")
    plt.close()
    #计算不同方法倍数关系
    print("Utility")
    multiple = {}
    for j in utilityDict:
        if j !='OPT':
            temp=0
            nu = 0
            for k in utilityDict[j]:
                temp += k
                nu+=1
            temp = temp/nu
            multiple.update({j:temp})
    print(multiple)
    ETGOA = multiple["DQL(ours)"]
    for item in multiple:
        re = ETGOA/multiple[item]
        print("DQL(ours) up",item,":\t",str(round(re,2)))

def drawTime(timeDict:dict,idx:list[int]):
    plt.figure(figsize=(figsize[0], figsize[1]), dpi=dpi)
    # plt.rcParams['font.sans-serif'] = ['STSong']  # 显示汉字
    plt.xlabel('$c_{w}$', fontsize=fontsize+6)  # x轴标题
    plt.ylabel('Time(secs)', fontsize=fontsize+6)  # y轴标题
    plt.tick_params(labelsize=fontsize)
    # 自定义横坐标的刻度
    # scale = np.arange(len(idx))
    plt.xticks(scale, idx)
    plt.yticks(rotation=60)

    # ax = plt.gca()
    # ax.ticklabel_format(style='sci', scilimits=(-1, 2), axis='y', useMathText='%.2f×10$^{4}$')
    # ax.get_yaxis().get_offset_text().set(va='bottom', ha='left')
    # ax.yaxis.get_offset_text().set_fontsize(8)

    colorNum = 0
    itemName = []
    for item in timeDict:
        if item == 'OPT':
            colorNum+=1
            continue
        itemName.append(item)
        plt.plot(scale, timeDict[item], markers[colorNum], color=colors[colorNum], linewidth=linewidth,
                 markersize=markersize,
                 markerfacecolor='none')
        colorNum += 1
    plt.legend(itemName)  # 设置折线名称
    # plt.show()
    plt.savefig("picture/gMissionTime.png")
    plt.close()
    #计算不同方法倍数关系
    print("Time")
    multiple = {}
    for j in timeDict:
        if j !='OPT':
            temp=0
            nu = 0
            for k in timeDict[j]:
                temp += k
                nu+=1
            temp = temp/nu
            multiple.update({j:temp})
    print(multiple)
    ETGOA = multiple["DQL(ours)"]
    for item in multiple:
        re = multiple[item]/ETGOA
        print("DQL(ours) up",item,":\t",str(round(re,2)))

def drawMemory(memoryDict:dict,idx:list[int]):
    plt.figure(figsize=(figsize[0], figsize[1]), dpi=dpi)
    # plt.rcParams['font.sans-serif'] = ['STSong']  # 显示汉字
    plt.xlabel('$c_{w}$', fontsize=fontsize+6)  # x轴标题
    plt.ylabel('Memory(KB)', fontsize=fontsize+6)  # y轴标题
    plt.tick_params(labelsize=fontsize)
    # 自定义横坐标的刻度
    # scale = np.arange(len(idx))
    plt.xticks(scale, idx)
    plt.yticks(rotation=60)

    ax = plt.gca()
    ax.ticklabel_format(style='sci', scilimits=(-1, 2), axis='y', useMathText='%.2f×10$^{4}$')
    ax.get_yaxis().get_offset_text().set(va='bottom', ha='left')
    ax.yaxis.get_offset_text().set_fontsize(8)

    colorNum = 0
    itemName = []
    for item in memoryDict:
        if item == 'OPT':
            colorNum += 1
            continue
        itemName.append(item)
        plt.plot(scale, memoryDict[item], markers[colorNum], color=colors[colorNum], linewidth=linewidth,
                 markersize=markersize,
                 markerfacecolor='none')
        colorNum += 1
    plt.legend(itemName)  # 设置折线名称
    # plt.show()
    plt.savefig("picture/gMissionMemory.png")
    plt.close()
    #计算不同方法倍数关系
    print("Momery")
    multiple = {}
    for j in memoryDict:
        if j !='OPT':
            temp=0
            nu = 0
            for k in memoryDict[j]:
                temp += k
                nu+=1
            temp = temp/nu
            multiple.update({j:temp})
    print(multiple)
    BGOA = multiple["DQL(ours)"]
    for item in multiple:
        re = (multiple[item]-BGOA)/multiple[item]
        print("DQL(ours) down",item,":\t",str(round(re*100,2)),"%")

def drawResponse(responseDict:dict,idx:list[int]):
    plt.figure(figsize=(figsize[0], figsize[1]), dpi=dpi)
    # plt.rcParams['font.sans-serif'] = ['STSong']  # 显示汉字
    plt.xlabel('$c_{w}$', fontsize=fontsize+6)  # x轴标题
    plt.ylabel('ARRTT(secs)', fontsize=fontsize+6)  # y轴标题  Average Real Response Time of Tasks
    plt.tick_params(labelsize=fontsize)
    # 自定义横坐标的刻度
    # scale = np.arange(len(idx))
    plt.xticks(scale, idx)

    ax = plt.gca()
    ax.ticklabel_format(style='sci', scilimits=(-1, 2), axis='y', useMathText='%.2f×10$^{4}$')
    ax.get_yaxis().get_offset_text().set(va='bottom', ha='left')
    ax.yaxis.get_offset_text().set_fontsize(8)

    colorNum = 0
    itemName = []
    for item in responseDict:
        if item == 'OPT':
            colorNum += 1
            continue
        itemName.append(item)
        plt.plot(scale, responseDict[item], markers[colorNum], color=colors[colorNum], linewidth=linewidth,
                 markersize=markersize,
                 markerfacecolor='none')
        colorNum += 1
    plt.legend(itemName)  # 设置折线名称
    # plt.show()
    plt.savefig("picture/gMissionResponse.png")
    plt.close()
    #计算不同方法倍数关系
    print("Response")
    multiple = {}
    for j in responseDict:
        if j !='OPT':
            temp=0
            nu = 0
            for k in responseDict[j]:
                temp += k
                nu+=1
            temp = temp/nu
            multiple.update({j:temp})
    print(multiple)
    BGOA = multiple["DQL(ours)"]
    for item in multiple:
        re = multiple[item]/BGOA
        print("DQL(ours) up",item,":\t",str(round(re,2)))

def drawMatchSize(matchSizeDict:dict,idx:list[int]):
    plt.figure(figsize=(figsize[0], figsize[1]), dpi=dpi)
    # plt.rcParams['font.sans-serif'] = ['STSong']  # 显示汉字
    plt.xlabel('$c_{w}$', fontsize=fontsize+6)  # x轴标题
    plt.ylabel('Matching Size', fontsize=fontsize+6)  # y轴标题  
    plt.tick_params(labelsize=fontsize)
    # 自定义横坐标的刻度
    # scale = np.arange(len(idx))
    plt.xticks(scale, idx)

    ax = plt.gca()
    ax.ticklabel_format(style='sci', scilimits=(-1, 2), axis='y', useMathText='%.2f×10$^{4}$')
    ax.get_yaxis().get_offset_text().set(va='bottom', ha='left')
    ax.yaxis.get_offset_text().set_fontsize(8)

    colorNum = 0
    itemName = []
    for item in matchSizeDict:
        # if item == 'OPT':
        #     colorNum += 1
        #     continue
        itemName.append(item)
        plt.plot(scale, matchSizeDict[item], markers[colorNum], color=colors[colorNum], linewidth=linewidth,
                 markersize=markersize,
                 markerfacecolor='none')
        colorNum += 1
    plt.legend(itemName)  # 设置折线名称
    plt.legend(itemName,loc=10, bbox_to_anchor=(0.5, 0.7))
    # plt.show()
    plt.savefig("picture/gMissonMatchSize.png")
    plt.close()   
    print("MatchSize")
    multiple = {}
    for j in matchSizeDict:
        if j !='OPT':
            temp=0
            nu = 0
            for k in matchSizeDict[j]:
                temp += k
                nu+=1
            temp = temp/nu
            multiple.update({j:temp})
    print(multiple)
    BGOA = multiple["DQL(ours)"]
    for item in multiple:
        re = multiple[item]/BGOA
        print("DQL(ours) up",item,":\t",str(round(re,2)))

if __name__ =='__main__':
    ddlList=[1,2,3,4,5,6,7,8,9,10]
    draw(ddlList, "data/varygMissionCw.txt")
